<script setup>
import TableBase from '@/components/Table-Base.vue'
import { ref } from 'vue'
import TablePagination from '@/components/Table-Pagination.vue'
import { addRuleItem, delRuleItem, editRuleItem, getRuleItem, getRulesList } from '@/api/rules'
import { MessagePlugin } from 'tdesign-vue-next'
import DialogBase from '@/components/Dialog-Base.vue'
import MainContent from '@/components/Main-Content.vue'

const chargeTypeMap = {
    'duration': '时长收费',
    'turn': '按次收费',
    'partition': '分段收费'
}
const query = ref({
    page: 1,
    pageSize: 10
})
const listData = ref({
    list: [],
    total: 0
})
const columns = ref([
    {
        title: '序号',
        colKey: 'serial-number',
        width: 80
    },
    {
        title: '规则编号',
        colKey: 'ruleNumber'
    },
    {
        title: '规则名称',
        colKey: 'ruleName'
    },
    {
        title: '计费方式',
        colKey: 'chargeType'
    },
    {
        title: '免费时长（分）',
        colKey: 'freeDuration',
        width: 150
    },
    {
        title: '收费上限（元）',
        colKey: 'chargeCeiling',
        width: 150
    },
    {
        title: '计费规则',
        colKey: 'ruleNameView',
        ellipsis: true
    },
    {
        title: '操作',
        colKey: 'option'
    }
])
const showDialog = ref(false)
const dialogType = ref('add')
const rules = ref({
    ruleNumber: [
        { required: true, message: '请输入规则编号', trigger: 'blur' },
        { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9]*$/, message: '请输入英文或数字', trigger: 'blur' }
    ],
    ruleName: [
        { required: true, message: '请输入规则名称', trigger: 'blur' },
        { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' }
    ]
})
const dialogForm = ref({
    chargeType: 'duration'
})
const ruleInfo = ref({})
const dialogFormInstance = ref(null)

const search = async () => {
    const res = await getRulesList(query.value)
    listData.value.list = res.data.rows.map(e => {
        e.chargeType = chargeTypeMap[e.chargeType]
        return e
    })
    listData.value.total = res.data.total
}
const addRule = async () => {
    dialogType.value = 'add'
    showDialog.value = true
}
const getRow = async (data, type) => {
    if (type === 'edit') {
        showDialog.value = true
        dialogType.value = 'edit'
        const res = (await getRuleItem(data.row.id)).data
        dialogForm.value = res
        ruleInfo.value = res
    } else {
        const res = await delRuleItem(data.row.id)
        if (res.code === 10000) {
            await MessagePlugin.success('删除成功!')
            if (listData.value.list.length === 1 && query.value.page > 1) query.value.page--
            await search()
        } else {
            await MessagePlugin.error(res.msg)
        }
    }
}
const changePage = e => {
    query.value.page = e.current
    query.value.pageSize = e.pageSize
    search()
}
const closeDialog = () => {
    showDialog.value = false
    dialogFormInstance.value.clearValidate()
}
const clickClose = () => {
    showDialog.value = false
    dialogFormInstance.value.reset()
    dialogForm.value = {
        chargeType: 'duration'
    }
    ruleInfo.value = {}
}
const dialogConfirm = async () => {
    const valid = await dialogFormInstance.value.validate()
    if (typeof valid === 'boolean' && valid) {
        if (dialogType.value === 'add') {
            const res = await addRuleItem({
                ...dialogForm.value,
                ...ruleInfo.value
            })
            if (res.code !== 10000) return
            clickClose()
            await MessagePlugin.success('添加成功！')
            await search()
        } else {
            const res = await editRuleItem({
                ...dialogForm.value,
                ...ruleInfo.value
            })
            if (res.code !== 10000) return
            clickClose()
            await MessagePlugin.success('修改成功！')
            await search()
        }
    }
}

search()
</script>

<template>
    <main-content>
        <table-base :columns="columns" :list="listData.list">
            <template #top-btn>
                <div style="margin-bottom: 20px; display: flex; justify-content: space-between;">
                    <t-button theme="primary" @click="addRule" style="margin-right: 10px">添加计费规则</t-button>
                </div>
            </template>
            <template #option-table="row">
                <t-button variant="text" theme="primary" @click="getRow(row, 'edit')">编辑</t-button>
                <t-popconfirm
                    destroyOnClose
                    showArrow
                    @confirm="getRow(row, 'del')"
                    theme="warning" content="确认删除吗">
                    <t-button variant="text" theme="primary">删除</t-button>
                </t-popconfirm>
            </template>
        </table-base>

        <table-pagination :total="listData.total" @changePage="changePage"></table-pagination>

        <dialog-base :showDialog="showDialog"
                     :dialogType="dialogType"
                     :dialogTitle="dialogType === 'add' ? '添加计费规则' : '编辑计费规则'"
                     @dialogConfirm="dialogConfirm"
                     @clickClose="clickClose"
                     @closeDialog="closeDialog">
            <t-form class="dialogForm" ref="dialogFormInstance" labelAlign="top" :rules="rules" :data="dialogForm">
                <t-form-item label="规则编号" name="ruleNumber">
                    <t-input placeholder="请输入规则编号" v-model.trim="dialogForm.ruleNumber"/>
                </t-form-item>
                <t-form-item label="规则名称" name="ruleName">
                    <t-input placeholder="请输入规则名称" v-model.trim="dialogForm.ruleName"/>
                </t-form-item>
                <t-form-item label="免费时长" name="freeDuration">
                    <t-input-adornment append="分钟">
                        <t-input-number placeholder="请输入免费时长"
                                        v-model.trim="dialogForm.freeDuration"
                                        theme="column" min="0" max="100000" :allowInputOverLimit="false"/>
                    </t-input-adornment>
                </t-form-item>
                <t-form-item label="收费上限" name="chargeCeiling">
                    <t-input-adornment append="元">
                        <t-input-number placeholder="请输入收费上限"
                                        v-model.trim="dialogForm.chargeCeiling"
                                        theme="column" min="0" max="999" :allowInputOverLimit="false"/>
                    </t-input-adornment>
                </t-form-item>
                <t-form-item label="计费方式" name="ruleType">
                    <t-radio-group variant="primary-filled" v-model.trim="dialogForm.chargeType">
                        <t-radio-button value="duration">时长收费</t-radio-button>
                        <t-radio-button value="turn">按次收费</t-radio-button>
                        <t-radio-button value="partition">分段收费</t-radio-button>
                    </t-radio-group>
                </t-form-item>

                <t-form-item label="计费规则" name="ruleInfo" v-if="dialogForm.chargeType === 'duration'">
                    <t-input-adornment prepend="每">
                        <t-input-number placeholder="请输入时长"
                                        v-model.trim="ruleInfo.durationTime"
                                        theme="column" min="1" max="1440" :allowInputOverLimit="false"/>
                    </t-input-adornment>
                    <t-select
                        style="margin: 0 10px; width: 100px"
                        placeholder="时间单位"
                        filterable
                        showArrow
                        v-model.trim="ruleInfo.durationType">
                        <t-option key="minute" label="分钟" value="minute" />
                        <t-option key="hour" label="小时" value="hour" />
                    </t-select>
                    <t-input-adornment prepend="收费" append="元">
                        <t-input-number placeholder="请输入金额"
                                        v-model.trim="ruleInfo.durationPrice"
                                        theme="column" min="1" max="100000" :allowInputOverLimit="false"/>
                    </t-input-adornment>
                </t-form-item>

                <t-form-item label="计费规则" name="ruleInfo" v-else-if="dialogForm.chargeType === 'turn'">
                    <t-input-adornment prepend="每次收费" append="元">
                        <t-input-number placeholder="请输入金额"
                                        v-model.trim="ruleInfo.turnPrice"
                                        theme="column" min="1" max="100000" :allowInputOverLimit="false"/>
                    </t-input-adornment>
                </t-form-item>

                <t-form-item label="计费规则" name="ruleInfo" v-else class="last-ruleInfo">
                    <div>
                        <t-input-adornment append="小时内">
                            <t-input-number placeholder="请输入时长"
                                            v-model.trim="ruleInfo.partitionFrameTime"
                                            theme="column" min="1" max="1440" :allowInputOverLimit="false"/>
                        </t-input-adornment>

                        <t-input-adornment prepend="每小时收费" append="元">
                            <t-input-number placeholder="请输入金额"
                                            v-model.trim="ruleInfo.partitionFramePrice"
                                            theme="column" min="1" max="100000" :allowInputOverLimit="false"/>
                        </t-input-adornment>
                    </div>
                    <div>
                        <t-input-adornment prepend="每增加" append="小时">
                            <t-input-number placeholder="请输入时长"
                                            v-model.trim="ruleInfo.partitionIncreaseTime"
                                            theme="column" min="1" max="1440" :allowInputOverLimit="false"/>
                        </t-input-adornment>

                        <t-input-adornment prepend="额外收费" append="元">
                            <t-input-number placeholder="请输入金额"
                                            v-model.trim="ruleInfo.partitionIncreasePrice"
                                            theme="column" min="1" max="100000" :allowInputOverLimit="false"/>
                        </t-input-adornment>
                    </div>
                </t-form-item>
            </t-form>
        </dialog-base>
    </main-content>
</template>

<style scoped lang="scss">
:deep .t-dialog__position {
    padding-top: 15vh;

    .t-dialog {
        width: 650px;

        .t-dialog__body {
            height: 550px;

            .t-input-adornment {
                flex: 1;

                .t-input-number {
                    flex: 1;
                }
            }

            .last-ruleInfo {
                .t-form__controls-content {
                    display: block;

                    > div {
                        display: flex;

                        > div:first-child {
                            margin-right: 10px;
                        }
                    }

                    > div:first-child {
                        margin-bottom: 10px;
                    }
                }
            }
        }
    }
}


:deep .t-popup__content {
    width: 100px;
}
</style>
